import { NextResponse } from 'next/server';
const Dysmsapi20170525 = require('@alicloud/dysmsapi20170525');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');

class SmsClient {
    static createClient() {
        let config = new OpenApi.Config({
            accessKeyId: process.env.ACCESSKEYID,
            accessKeySecret: process.env.ACCESSKEYSECRET,
        });
        config.endpoint = 'dysmsapi.aliyuncs.com';
        return new Dysmsapi20170525.default(config);
    }

    static async sendSms(phoneNumber, templateParam) {
        const client = SmsClient.createClient();
        const sendSmsRequest = new Dysmsapi20170525.SendSmsRequest({
            phoneNumbers: phoneNumber,
            signName: process.env.SIGNNAME,
            templateCode: process.env.TEMPLATECODE,
            templateParam: JSON.stringify({ code: templateParam }),
        });
        let runtime = new Util.RuntimeOptions({
            //设置超时时间
            connectTimeout: 30000,
        });
        try {
            const response = await client.sendSmsWithOptions(sendSmsRequest, runtime);
            return response;
        } catch (error) {
            throw error;
        }
    }
}

export async function POST(request) {

    const { phone, code } = await request.json();

    try {
        const response = await SmsClient.sendSms(phone, code);
        return NextResponse.json({ success: true, data: response, code: 'cdode' });
    } catch (error) {
        return NextResponse.json({ success: false, error: error.message }, { status: 500 });
    }
}